﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;

namespace Framework.WebmasterTool.Memberships
{
    public partial class ManageUsers : System.Web.UI.Page
    {
        public DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public string GridViewSortExpression
        {
            get { return ViewState["GridViewSortExpression"] == null ? "UserName" : ViewState["GridViewSortExpression"] as string; }
            set { ViewState["GridViewSortExpression"] = value; }
        }
        public SortDirection GridViewSortOrder
        {
            get { return ViewState["GridViewSortOrder"] == null ? SortDirection.Ascending : (SortDirection)ViewState["GridViewSortOrder"]; }
            set { ViewState["GridViewSortOrder"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                LoadRoles();
                LoadMembers();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.ManagerUser.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void LoadRoles()
        {
            string strAdministrator = "Super Administrator";
            MembershipUser currentUser = Membership.GetUser();
            if (currentUser != null && Roles.IsUserInRole(currentUser.UserName, strAdministrator) == true)
            {
                string[] allRoles = Roles.GetAllRoles();
                ddlRoles.DataSource = allRoles;
                ddlRoles.DataBind();
            }
            else
            {
                string[] allRoles = Roles.GetAllRoles();
                ddlRoles.DataSource = allRoles.Where(rl => !rl.Contains(strAdministrator));
                ddlRoles.DataBind();
            }
        }

        public void LoadMembers()
        {
            var members = entity.udv_Users.Where(us => us.Visible != false).Select(mb => new { mb.UserName, mb.Email, FullName = mb.FirstName.Trim() + " " + mb.LastName.Trim(), mb.AddedDate }).ToList();
            var rows = members.Select(mb => new { mb.UserName, mb.Email, mb.FullName, mb.AddedDate, RoleName = GetRolesByUsername(mb.UserName) }).ToList();
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                rows = rows.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                rows = rows.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvMemberShip.DataSource = rows;
            grvMemberShip.DataBind();
            lblTotalMemberShip.Text = rows.Count.ToString();
        }

        public string GetRolesByUsername(string username)
        {
            string[] rolesOfUsername = Roles.GetRolesForUser(username);
            string roles = "";
            foreach (var item in rolesOfUsername)
            {
                roles += item + ", ";
            }
            roles = roles.Trim();
            return roles.Substring(0, roles.Length - 1);
        }

        protected void grvMemberShip_Sorting(object sender, GridViewSortEventArgs e)
        {
            //Check if the same column is sorted to switch Sort Order  
            if (GridViewSortExpression.Equals(e.SortExpression))
                GridViewSortOrder = GridViewSortOrder.Equals(SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
            else
                GridViewSortOrder = SortDirection.Ascending;
            //save Sort Expression and Sort Order
            GridViewSortExpression = e.SortExpression;
            if (grvMemberShip.ToolTip == "all")
                LoadMembers();
            else
                SearchMembers();
        }

        protected void grvMemberShip_DataBinding(object sender, EventArgs e)
        {
            string srcImageASC = Globals.ApplicationPath + "WebmasterTool/Images/ASC.gif";
            string srcImageDESC = Globals.ApplicationPath + "WebmasterTool/Images/DESC.gif";
            foreach (DataControlField column in grvMemberShip.Columns)
            {
                //Remove Previous Sort Image  
                column.HeaderText = Regex.Replace(column.HeaderText, "<[^>]*>", "", RegexOptions.IgnoreCase);
                if (column.SortExpression.Equals(GridViewSortExpression))
                {
                    //set new sort image  
                    string strSortImageURL = GridViewSortOrder == SortDirection.Descending ?
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageDESC + "' />" :
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageASC + "' />";
                    column.HeaderText = String.Format("{0}{1}", column.HeaderText, strSortImageURL);
                }
            }
        }

        protected void grvMemberShip_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvMemberShip.PageIndex = e.NewPageIndex;
            if (grvMemberShip.ToolTip == "all")
                LoadMembers();
            else
                SearchMembers();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            grvMemberShip.PageIndex = 0;
            grvMemberShip.ToolTip = "search";
            SearchMembers();
        }

        private void SearchMembers()
        {
            var members = entity.udv_Users.Where(us => us.Visible != false).Select(mb => new { mb.UserName, mb.Email, FullName = mb.FirstName.Trim() + " " + mb.LastName.Trim(), mb.AddedDate }).ToList();
            var rows = members.Select(mb => new { mb.UserName, mb.Email, mb.FullName, mb.AddedDate, RoleName = GetRolesByUsername(mb.UserName) }).ToList();
            if (txtSearch.Text.Trim() == "" && ddlRoles.SelectedValue.Trim() != "0")
            {
                string roles = ddlRoles.SelectedValue.Trim().ToLower();
                rows = rows.Where(mb => mb.RoleName.ToLower().Contains(roles)).ToList();
            }
            else if (txtSearch.Text.Trim() != "" && ddlRoles.SelectedValue.Trim() == "0")
            {
                string keywordSearch = txtSearch.Text.Trim().ToLower();
                rows = rows.Where(mb => mb.UserName.ToLower().Contains(keywordSearch) || mb.Email.ToLower().Contains(keywordSearch) || Globals.RemoveSign4VietnameseString(mb.FullName.ToLower()).Contains(keywordSearch) || mb.AddedDate.Value.ToString("dd/MM/yyyy").Contains(keywordSearch)).ToList();
            }
            else if (txtSearch.Text.Trim() != "" && ddlRoles.SelectedValue.Trim() != "0")
            {
                string roles = ddlRoles.SelectedValue.Trim().ToLower();
                string keywordSearch = txtSearch.Text.Trim().ToLower();
                rows = rows.Where(mb => (mb.UserName.ToLower().Contains(keywordSearch) || mb.Email.ToLower().Contains(keywordSearch) || Globals.RemoveSign4VietnameseString(mb.FullName.ToLower()).Contains(keywordSearch) || mb.AddedDate.Value.ToString("dd/MM/yyyy").Contains(keywordSearch)) && mb.RoleName.ToLower().Contains(roles)).ToList();
            }
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                rows = rows.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                rows = rows.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvMemberShip.DataSource = rows;
            grvMemberShip.DataBind();
            lblTotalMemberShip.Text = rows.Count.ToString();
        }

        protected void btnCreateAccount_Click(object sender, EventArgs e)
        {
            Response.Redirect("CreateUser.aspx");
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in grvMemberShip.Rows)
            {
                bool isChecked = ((HtmlInputCheckBox)row.FindControl("chkSelect")).Checked;
                if (isChecked)
                {
                    string UserName = (((HtmlInputCheckBox)row.FindControl("chkSelect")).Attributes["title"].Trim());
                    Membership.DeleteUser(UserName);

                    //create db log
                    CreateDBLog(null, null, TypeAction.Delete, "Xoá thành viên: " + UserName, "", "", "", "",
                        "", "", "", "");
                }
            }
            //data cache
            Cache.Remove("User");
            if (grvMemberShip.ToolTip == "all")
                LoadMembers();
            else
                SearchMembers();
        }

        protected void btnManagerGroup_Click(object sender, EventArgs e)
        {
            Response.Redirect("ManagerGroups.aspx");
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}